using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading.Tasks;
using WPF_MVVM_Test.MVVM_Model;
using WPF_MVVM_Test.MVVM_Model.ProductionOrder;

namespace WPF_MVVM_Test.Services.ProductionOrder
{
    public class ProductionOrderService
    {
        private readonly HttpClient _httpClient;
        private readonly JsonSerializerOptions _jsonOptions;

        public ProductionOrderService()
        {
            _httpClient = new HttpClient();
            _jsonOptions = new JsonSerializerOptions
            {
                PropertyNameCaseInsensitive = true
            };
        }

        /// <summary>
        /// 获取生产工单物料清单
        /// </summary>
        /// <param name="productionOrderId">生产工单ID</param>
        /// <returns></returns>
        public async Task<ProductionOrderMaterialResponse> GetProductionOrderMaterialListAsync(string productionOrderId)
        {
            try
            {
                var url = $"http://8.140.242.140:8888/api/ProductionOrder/GetProductionOrderMaterialList/material-list/{productionOrderId}";
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 请求物料清单URL: {url}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 生产工单ID: {productionOrderId}");
                
                var response = await _httpClient.GetAsync(url);
                
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料清单API响应状态码: {response.StatusCode}");
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料清单API响应内容: {jsonString}");
                    
                    var result = JsonSerializer.Deserialize<ProductionOrderMaterialResponse>(jsonString, _jsonOptions);
                    
                    if (result != null)
                    {
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料清单数据解析成功");
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] IsSuc: {result.IsSuc}");
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Code: {result.Code}");
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Msg: {result.Msg}");
                        System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] Data是否为null: {result.Data == null}");
                        
                        if (result.Data?.Materials != null)
                        {
                            System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料数量: {result.Data.Materials.Count}");
                        }
                    }
                    
                    return result ?? new ProductionOrderMaterialResponse { IsSuc = false, Msg = "数据解析失败" };
                }
                else
                {
                    var errorContent = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 物料清单API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                    System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 错误响应内容: {errorContent}");
                    
                    return new ProductionOrderMaterialResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.StatusCode} - {response.ReasonPhrase}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 获取物料清单异常: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"[{DateTime.Now:HH:mm:ss.fff}] 异常堆栈: {ex.StackTrace}");
                
                return new ProductionOrderMaterialResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取生产工单工艺路线
        /// </summary>
        /// <param name="productionOrderId">生产工单ID</param>
        /// <param name="includeDeleted">是否包含已删除</param>
        /// <returns></returns>
        public async Task<ProductionOrderRoutingResponse> GetProductionOrderRoutingAsync(string productionOrderId, bool includeDeleted = true)
        {
            try
            {
                var url = $"http://8.140.242.140:8888/api/ProductionOrder/GetProductionOrderRouting/routing/{productionOrderId}?includeDeleted={includeDeleted}";
                
                System.Diagnostics.Debug.WriteLine($"请求工艺路线URL: {url}");
                
                var response = await _httpClient.GetAsync(url);
                
                if (response.IsSuccessStatusCode)
                {
                    var jsonString = await response.Content.ReadAsStringAsync();
                    System.Diagnostics.Debug.WriteLine($"工艺路线API响应: {jsonString}");
                    
                    var result = JsonSerializer.Deserialize<ProductionOrderRoutingResponse>(jsonString, _jsonOptions);
                    return result ?? new ProductionOrderRoutingResponse { IsSuc = false, Msg = "数据解析失败" };
                }
                else
                {
                    return new ProductionOrderRoutingResponse
                    {
                        IsSuc = false,
                        Code = (int)response.StatusCode,
                        Msg = $"请求失败: {response.ReasonPhrase}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"获取工艺路线异常: {ex.Message}");
                return new ProductionOrderRoutingResponse
                {
                    IsSuc = false,
                    Code = 500,
                    Msg = $"请求异常: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 更新生产工单状态
        /// </summary>
        /// <param name="request">更新状态请求</param>
        /// <returns></returns>
        public async Task<ApiResponse> UpdateProductionOrderStatusAsync(UpdateProductionOrderStatusRequest request)
        {
            try
            {
                var url = "http://8.140.242.140:8888/api/ProductionOrder/UpdateProductionOrderStatus";
                
                System.Diagnostics.Debug.WriteLine($"更新生产工单状态URL: {url}");
                System.Diagnostics.Debug.WriteLine($"更新状态请求: Id={request.Id}, Status={request.Status}, UpdatedBy={request.UpdatedBy}");
                
                var jsonContent = JsonSerializer.Serialize(request, _jsonOptions);
                var content = new StringContent(jsonContent, System.Text.Encoding.UTF8, "application/json");
                
                var response = await _httpClient.PostAsync(url, content);
                var responseContent = await response.Content.ReadAsStringAsync();
                
                System.Diagnostics.Debug.WriteLine($"更新状态API响应: {responseContent}");
                
                if (response.IsSuccessStatusCode)
                {
                    var result = JsonSerializer.Deserialize<ApiResponse>(responseContent, _jsonOptions);
                    return result ?? new ApiResponse { Success = false, Message = "数据解析失败" };
                }
                else
                {
                    System.Diagnostics.Debug.WriteLine($"更新状态API请求失败: {response.StatusCode} - {response.ReasonPhrase}");
                    return new ApiResponse
                    {
                        Success = false,
                        Code = (int)response.StatusCode,
                        Message = $"请求失败: {response.ReasonPhrase}"
                    };
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine($"更新生产工单状态异常: {ex.Message}");
                return new ApiResponse
                {
                    Success = false,
                    Code = 500,
                    Message = $"请求异常: {ex.Message}"
                };
            }
        }
    }
}


